# -*- coding: UTF-8 -*-
import pygame
import maploader
from pygame.locals import *
from Perso import *
import ServerHandler
import ObjectHandler
import time
import hashlib
from threading import*

def Init(mapname):
	#initialisation du scrolling
	global scrollx
	global scrolly
	global screen
	global ObjectHandler
	scrollx = 0
	scrolly = 0
	pygame.init()
	ObjectHandler = ObjectHandler.ObjectHandler()
	#initialisation de la fenetre
	screen = pygame.display.set_mode((1024,768), DOUBLEBUF)
	ico = pygame.image.load("LOZSO.png")
	pygame.display.set_icon(ico)
	pygame.display.set_caption("Legend Of Zelda: Swords Online")
	c
	#chargement de la map
	maploader.loadMap("testmap.tmx")
	#Touches en mode repeter
	pygame.key.set_repeat(10, 10)

def Logging():
	global server
	print "Bonjour..."
	print "Bienvenue dans LOZ: Swords Online version alpha 0.000000000001"
	print "Identifiant:"
	identif = str(raw_input())
	print "Mot de passe:"
	mdp = hashlib.sha1(raw_input()).hexdigest()
	server = ServerHandler.Server()
	if server.connect("zorvalt.is-a-geek.net", identif, mdp) == False:
		print "Conexion echouee --'"
		print "Exiting..."
		time.sleep(2)
		return False
	else:
		print "Connexion reussie!"
		Init(server.getInitInfo())

		
def Scrolling(link):
	scrollx = (400-link.posx)*0.9 + scrollx*0.1
	scrolly = (300-link.posy)*0.9 + scrolly*0.1

def Main():
	if Logging() == False:
		return
	#server.connect("zorvalt.is-a-geek.net", "greg", "lol")
	#retire les images de la map
	image1, image2 = maploader.getImages()
	#retire le tableau de collisions
	collisionmap = maploader.getCollisionArray()
	#creation du personnage
	link = Perso([320,140])
	dir = [0,0]
	#thread de gestion reseau:
	continuer = True
	thread = Thread(target = server.commandsTread, args = (continuer, ObjectHandler))
	thread.start()
	while 1:
			dir = [0,0]
			for event in pygame.event.get():
				if event.type == QUIT:
					return
				elif event.type == KEYDOWN and event.key == K_ESCAPE:
					return
				elif event.type == KEYDOWN:
					if event.key == K_LEFT:
						dir[0] -= 1
					if event.key == K_RIGHT:
						dir[0] += 1
					if event.key == K_UP:
						dir[1] -= 1
					if event.key == K_DOWN:
						dir[1] += 1
			link.update(dir, collisionmap, server, scrollx, scrolly)
			ObjectHandler.Draw(screen, image1, image2, (scrollx, scrolly), link)
			#Scrolling(link)
			screen.blit(image2, (scrollx,scrolly))
			pygame.display.flip()
			time.sleep(0.03)
Main()
